<template>
  <el-dialog :title="title" :visible.sync="visible" width="1000px" append-to-body :show-close="true" :close-on-click-modal="false" :size="size" >
    <div class="images-condition-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="商品编码" prop="gNumber">
          <el-input v-model="queryParams.gNumber" placeholder="请输入商品编码" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="商品名称" prop="gName">
          <el-input v-model="queryParams.gName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="图片名称" prop="imageName">
          <el-input v-model="queryParams.imageName" placeholder="请输入图片名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="delFlag">
          <el-select v-model="queryParams.delFlag" placeholder="图片状态" clearable>
            <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
                       :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item style="float: right;">
          <el-button icon="el-icon-search" class="query-btn" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" class="reset-btn" @click="resetQuery">重置</el-button>
          <el-button icon="el-icon-upload2" class="upload-btn" @click="handleUpload">上传</el-button>
          <el-button icon="el-icon-finished" class="config-btn" @click="handleSubmit">确 定</el-button>
          <el-button icon="el-icon-close" class="cancel-btn" @click="visible = false">取 消</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="20">
        <!--图片类型-->
        <el-col :span="6" :xs="24">
          <div class="sidebar-body-container">
            <el-tree
              :data="dict.type.sys_goods_img_type"
              ref="tree"
              show-checkbox
              node-key="value"
              :default-checked-keys="queryParams.params.imageTypes"
              @check-change="handleNodeClick"
            />
          </div>
        </el-col>
        <!-- 图片数据 -->
        <el-col :span="18" :xs="24">
          <div class="images-list-container">
            <div>
              <el-checkbox v-model="checkedAll" :disabled="limit===1" @change="handleCheckAll" >全选/取消</el-checkbox>
            </div>
            <div class="list-container">
              <template v-for="(image, index) in list">
                <item-image :image="image" @delImage="delImage" @itemChecked="handleItemChecked(index)" />
              </template>
            </div>
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </div>
        </el-col>
      </el-row>
    </div>
    <upload-image ref="upload" :params="{ imageType: queryParams.params.imageTypes }" @ok="handleUploadOk" />
  </el-dialog>

</template>
<script>
import { findNoSelImagesList } from '@/api/goods/images'
import ItemImage from '@/views/goods/images/components/itemImage.vue'
import UploadImage from '@/views/goods/images/components/uploadImage.vue'

export default {
  components: { UploadImage, ItemImage },
  dicts: ['sys_goods_img_type', 'sys_goods_res_path', 'sys_normal_disable'],
  props: {
    params: {
      type: Object,
      default: {}
    }
  },
  computed: {
    size() {
      return this.$store.getters.size
    }
  },
  data() {
    return {
      visible: false,
      title: '选择图片',
      limit: 1,
      loading: false,
      checkedAll: false,
      showSearch: true,
      // 总条数
      total: 0,
      // 本地图片资源地址
      imgServe: process.env.VUE_APP_BASE_API,
      queryParams: {
        params: {
          imageTypes: []
        }
      },
      list: [],
    }
  },
  methods: {
    generateQueryParams() {
      return {
        pageNum: 1,
        pageSize: 10,
        gNumber: null,
        gName: null,
        imageType: null,
        imageName: null,
        imageServer: null,
        imagePath: null,
        orderNum: null,
        selectedList: [],
        params: {
          gNumber: null,
          imageTypes: []
        }
      }
    },
    // 显示弹框
    show() {
      this.queryParams = this.generateQueryParams();
      const params = this.params;
      if (params.gNumber) {
        this.queryParams.gNumber = params.gNumber;
        this.queryParams.params.gNumber = params.gNumber;
      }
      if (params.imageType) {
        const types = [ params.imageType ];
        this.queryParams.params.imageTypes = types;
        // this.queryParams.imageType = params.imageType;
      }
      if (params.selectedList) {
        const selectedList = params.selectedList;
        this.queryParams.selectedList = selectedList;
      }
      if (params.limit && params.limit >= 1) {
        this.limit = params.limit;
      } else {
        this.limit = 1;
      }
      this.getList();
      this.visible = true;
    },
    getList() {
      this.loading = true;
      this.list = [];
      this.checkedAll = false;
      findNoSelImagesList(this.queryParams).then(res => {
        let list = res.rows;
        const selectedList = this.queryParams.selectedList
        console.log('selectedList', selectedList)
        list?.forEach(item => {
          item.isSelected = false;
          if (selectedList && selectedList.length > 0) {
            if (selectedList.includes(item.imagePath)) {
              item.isDisabled = true;
              item.isSelected = true;
            }
          }
        })
        console.log('list', list)
        this.list = list;
        this.total = res.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSubmit() {
      let imagePaths = [];
      const list = this.list;
      for (let i = 0, len = list.length; i < len; i++) {
        if (!list[i].isDisabled && list[i].isSelected) {
          imagePaths.push({ 'imageId': list[i].imageId, 'imagePath': list[i].imagePath });
        }
      }
      if (imagePaths.length === 0) {
        this.$modal.msgError("请先选择图片");
      } else if (imagePaths.length > this.limit) {
        this.$modal.msgError('最多选择 ' + this.limit + ' 张图片');
      } else {
        this.visible = false;// 提交表单时触发自定义事件
        this.$emit('ok', imagePaths);
      }
    },
    // 节点单击事件
    handleNodeClick(data, checked, indeterminate) {
      if (checked) {
        const types = [ data.value ];
        this.queryParams.params.imageTypes = types
        this.$refs.tree.setCheckedKeys(types);
        this.handleQuery();
      } else {
        // this.queryParams.params.imageTypes = checkedTypes;
      }
    },
    handleCheckAll(checked) {
      this.list.forEach(item => {
        if (!item.isDisabled) {
          item.isSelected = checked;
        }
      });
    },
    handleItemChecked(index) {
      const list = this.list;
      if (this.limit === 1) {
        for (let i = 0; i < list.length; i++) {
          if (i !== index) {
            list[i].isSelected = false;
          }
        }
      } else {
        let checkedAll = true;
        for (let i = 0; i < list.length; i++) {
          if (!list[i].isSelected) {
            checkedAll = false;
          }
        }
        this.checkedAll = checkedAll;
      }
    },
    delImage(image) {
      console.log('delImage', image);
    },
    handleUploadOk() {
      this.handleQuery();
    },
    handleUpload() {
      this.$refs.upload.show();
    }
  }
}
</script>

<style scoped lang="scss">
.images-list-container {
  height: 550px;
}
.list-container {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
  height: 450px;
  overflow-y: auto; /* 垂直方向滚动 */
}
</style>
